﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting;
using System.Configuration;
using Shumi.UserCacheService.Common;
using Shumi.UserCacheService.BLL;

namespace Shumi.UserCacheService
{
    partial class UserCacheService : ServiceBase
    {
        public UserCacheService()
        {
            InitializeComponent();
        }

        int portNO = Convert.ToInt32(ConfigurationManager.AppSettings["Port"]);
        double userDataSyncInterval = Convert.ToDouble(ConfigurationManager.AppSettings["UserDataSyncInterval"]);
        TcpChannel tcpChnl;
        System.Timers.Timer t;

        protected override void OnStart(string[] args)
        {
            try
            {
                WellKnownObjectMode mode = WellKnownObjectMode.SingleCall;

                try
                {
                    mode = ConfigurationManager.AppSettings["ActiveMode"] == "singleton" ? WellKnownObjectMode.Singleton : WellKnownObjectMode.SingleCall;
                }
                catch
                {
                    mode = WellKnownObjectMode.SingleCall;
                }

                tcpChnl = new TcpChannel(portNO);
                ChannelServices.RegisterChannel(tcpChnl, false);

                Logger.Instance.Write(new LogEntity("用户缓存服务开始启动..."));
                RemotingConfiguration.RegisterWellKnownServiceType(typeof(BLL.UserManager), "UserManager", mode);
                RemotingConfiguration.RegisterWellKnownServiceType(typeof(BLL.UserSync), "UserSync", mode);
                Logger.Instance.Write(new LogEntity("用户缓存服务启动成功."));

                t = new System.Timers.Timer(userDataSyncInterval);
                t.Enabled = true;
                t.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed);
                t.Start();
            }
            catch (Exception ex)
            {
                Logger.Instance.Write(new LogEntity(string.Format("用户缓存服务启动发生异常，异常信息：{0}", ex.Message + Environment.NewLine + ex.StackTrace)));
            }

            Logger.Instance.Save();
        }

        void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            DateTime dt = DateTime.Now.AddMilliseconds(userDataSyncInterval * -1);
            UserManager um = new UserManager();
            um.UserDataSync(dt);
        }

        protected override void OnStop()
        {
            if (tcpChnl != null)
            {
                Logger.Instance.Write(new LogEntity("开始停止用户缓存服务..."));
                tcpChnl.StopListening(null);
                ChannelServices.UnregisterChannel(tcpChnl);
                Logger.Instance.Write(new LogEntity("用户缓存服务已停止."));
                Logger.Instance.Save();
            }

            t.Stop();
            //foreach (IChannel chnl in ChannelServices.RegisteredChannels)
            //{
            //    //注：若服务器上有两个Remoting应用，并都用TcpChannel，该方法要改写，根据TcpChannel名称来判断
            //    if (chnl.GetType().Name == "TcpChannel")
            //    {
            //        ((TcpChannel)chnl).StopListening(null);
            //        ChannelServices.UnregisterChannel(chnl);
            //    }
            //}
        }
    }
}
